<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        table {
            border: 2px solid;
            width: 600px;
            height: 300px;
            text-align: center;
        }

        td,
        th {
            border: dashed 1px;
        }
    </style>
</head>

<body>

    <table>
        <thead>
            <tr>
                <th></th>
                <th>商品</th>
                <th>单价</th>
                <th>购买数量</th>
                <th>操作</th>
                <th>总价</th>
            </tr>
        </thead>

        <tbody></tbody>
    </table>



    <script>
        let arr = [
            { id: 1, name: '苹果', price: 5, count: 2 },
            { id: 2, name: '葡萄', price: 8, count: 6 },
            { id: 3, name: '香蕉', price: 3, count: 4 },
            { id: 4, name: '橘子', price: 4, count: 4 }
        ]


        let tbody = document.getElementsByTagName('tbody')[0];
        function show() {
            let str = '', total = 0;
            arr.map((item) => {
                str += `
                <tr>
                    <td>${item.id}</td>
                    <td>${item.name}</td>
                    <td>${item.price}</td>
                    <td>${item.count}</td>
                    <td>
                        <button data-id=${item.id}>-</button>
                        <span>${item.count}</span>
                        <button data-id=${item.id}>+</button>
                    </td>
                    <td>${item.price * item.count}</td>
                </tr>
                `
                //每一种水果的总价
                total += item.price * item.count;
            })

            str += `
            <tr>
                <td colspan="6">总价：${total}</td>
            </tr>`
            tbody.innerHTML = str;

        }
        show()


        tbody.addEventListener('click', function (event) {
            //第一点的是第几行的按钮，第二点的是这一行的什么按钮
            let id = event.target.dataset.id;
            console.log(id);
            //拿到button得自定义id跟数组的id做匹配，操作匹配上的水果数量
            arr.map(function (item) {
                if (item.id == id) {
                    if (event.target.innerHTML == '-') {
                        item.count > 0 ? item.count-- : item.count = 0;
                    }
                    if (event.target.innerHTML == '+') {
                        item.count++
                    }
                }

            })
            show()


        })


    </script>

</body>

</html>